#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/6/22 14:39
# @Author : wn 
# @File: log.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡

import datetime
import json
from operator import itemgetter

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from trade.model_choices import *
from trade.models import *
from trade.search_page import search_log
from utils.service import my_page


class Log(View):
    def __init__(self):
        self.title = '日志管理'
        self.url = "/trade/log/"
        self.type = 'paper'

    def get(self, request):
        # 当前访问用户
        customerid = request.GET.get('customerid', None)
        if customerid:
            request.session['customerid'] = customerid
            print('get方式，当前访问的用户是：', customerid)
        off = request.GET.get('offset', None)
        lim = request.GET.get('limit', None)
        search = request.GET.get('search', None)
        if off is None:
            return render(request, "olog.html", {'url': self.url, 'title': self.title})
        else:
            result_list_sorted = []
            result_list = []
            tab_type = request.GET.get('type')
            # 操作日志，日志表
            if tab_type == '0':
                log_list = list(Operationlog.objects.using('quantWebDB').all())
                for item in log_list:
                    result_dict = {}
                    result_dict['sequenceno'] = item.sequenceno
                    result_dict['customerid'] = item.customerid
                    result_dict['modular'] = item.modular
                    result_dict['optfunction'] = LogContent.get(item.optfunction, None)
                    result_dict['optinfo'] = item.optinfo
                    result_dict['opttime'] = item.opttime
                    result_list.append(result_dict)
                # 排序
                for item in result_list:
                    if (item.get('sequenceno') is None):
                        item['sequenceno'] = '-1'
                result_list_sorted = sorted(result_list, key=itemgetter('sequenceno'), reverse=True)
            elif tab_type == '1':
                # 策略日志表
                today = datetime.datetime.now().strftime('%Y-%m-%d')
                tt = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')
                print(tt)
                stgLogList = Rulemessage.objects.using('quantPaperDB').filter(timestamp__contains=today)
                for item in stgLogList:
                    result_dict = {}
                    result_dict['timestamp'] = item.timestamp
                    result_dict['ruleid'] = item.ruleid
                    # 策略名
                    stg_qs = Strategy.objects.using('quantWebDB').filter(stgid=item.ruleid)
                    stgname = ''
                    if len(stg_qs) != 0:
                        stgname = stg_qs[0].stgname
                    result_dict['rulename'] = stgname
                    result_dict['messagelevel'] = LogLevel_ModelChoices.get(item.messagelevel, None)
                    result_dict['message'] = item.message
                    result_list.append(result_dict)
                    # 排序
                for item in result_list:
                    if (item.get('timestamp') is None):
                        item['timestamp'] = '-1'

                result_list_sorted = sorted(result_list, key=itemgetter('timestamp'), reverse=True)
            result = my_page(result_list_sorted, lim, off)
            return JsonResponse(result, safe=False)

    def post(self, request):
        if request.POST.get("search_log", None):
            # 前端查询条件
            data = json.loads(request.POST.get("data"))
            customerid = data.get("customerid", None)  # if no condition value is str ''
            optinfo = data.get("optinfo", None)  # if no condition value is str ''
            optfunction = data.get("optfunction", None)  # if no condition value is str ''

            jsonRes = search_log(customerid=customerid, optinfo=optinfo, optfunction=optfunction, type='0')
            return jsonRes
        elif request.POST.get("search_stglog", None):
            # 前端查询条件
            data = json.loads(request.POST.get("data"))
            envir_stglog = data.get("envir_stglog", None)
            timestamp_stglog = data.get("timestamp_stglog", None)  # if no condition value is str ''
            ruleid_stglog = data.get("ruleid_stglog", None)  # if no condition value is str ''
            rulename_stglog = data.get("rulename_stglog", None)  # if no condition value is str ''
            messagelevel_stglog = data.get("messagelevel_stglog", None)  # if no condition value is str ''

            jsonRes = search_log(envir=envir_stglog, logLevel=messagelevel_stglog, dateTime=timestamp_stglog,
                                 stgname=rulename_stglog, stgid=ruleid_stglog, type='1')
            return jsonRes
